package com.kingdee.eas.hr.train.client;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.ctrl.common.util.ControlUtilities;
import com.kingdee.bos.ctrl.extendcontrols.KDBizPromptBox;
import com.kingdee.bos.ctrl.kdf.table.ICell;
import com.kingdee.bos.ctrl.kdf.table.IRow;
import com.kingdee.bos.ctrl.kdf.table.KDTable;
import com.kingdee.bos.ctrl.kdf.util.style.StyleAttributes;
import com.kingdee.bos.ctrl.swing.KDContainer;
import com.kingdee.bos.ctrl.swing.KDWorkButton;
import com.kingdee.bos.ctrl.swing.event.DataChangeEvent;
import com.kingdee.bos.ctrl.swing.event.PreChangeEvent;
import com.kingdee.bos.ctrl.swing.event.PreChangeListener;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemCollection;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.entity.SorterItemCollection;
import com.kingdee.bos.metadata.entity.SorterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.ui.face.CoreUIObject;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.hr.emp.IPersonDegree;
import com.kingdee.eas.hr.emp.PersonDegreeCollection;
import com.kingdee.eas.hr.emp.PersonDegreeFactory;
import com.kingdee.eas.hr.emp.PersonDegreeInfo;
import com.kingdee.eas.hr.train.ChannelCoursE1Collection;
import com.kingdee.eas.hr.train.ChannelCoursE1Factory;
import com.kingdee.eas.hr.train.ChannelCoursE1Info;
import com.kingdee.eas.hr.train.IChannelCoursE1;
import com.kingdee.eas.hr.train.InstructorTypeInfo;
import com.kingdee.eas.hr.train.TrainConstants;
import com.kingdee.eas.hr.train.TrainCourseInfo;
import com.kingdee.eas.hr.train.TrainInstructorInfo;
import com.kingdee.eas.util.SysUtil;
import com.kingdee.eas.util.client.EASResource;
import com.kingdee.eas.util.client.MsgBox;
import java.awt.event.ActionEvent;
import java.text.ParseException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import org.apache.log4j.Logger;

public class BatchAddInstructorForCourseUI extends
		AbstractBatchAddInstructorForCourseUI {
	private static final Logger logger = CoreUIObject
			.getLogger(BatchAddInstructorForCourseUI.class);
	private static final String RESOURCE = "com.kingdee.eas.hr.train.client.TrainChanneResource";
	private static final String RES = "com.kingdee.eas.hr.train.client.TrainRecordResource";
	private static final String SYS_RESOURCE = "com.kingdee.eas.hr.train.client.TrainSysResource";
	static String RES1 = "com.kingdee.eas.hr.train.client.TrainRecordResource";
	private Map personDegrees;
	private TrainInstructorPromptBox instructorPromptBox;
	private String trainCourseID;
	private Set instructorHistoryIDSet = new HashSet();
	private Set instructorAddIDSet = new HashSet();
	private Set instructorRemoveIDSet = new HashSet();
	private LocateAssistant locateAssistant;

	public BatchAddInstructorForCourseUI() throws Exception {
	}

	public void onLoad() throws Exception {
		super.onLoad();
		this.tblMain.checkParsed();
		init();

		loadData();

		this.prmtTrainCourse.addPreChangeListener(new PreChangeListener() {
			public void preChange(PreChangeEvent e) {
				BatchAddInstructorForCourseUI.this.checkModify(e);
				BatchAddInstructorForCourseUI.this.prmtTrainCourse.setValue(e
						.getOldData());
			}
		});
	}

	protected void prmtTrainCourse_dataChanged(DataChangeEvent e)
			throws Exception {
		loadData();
		super.prmtTrainCourse_dataChanged(e);
	}

	private void loadData() throws BOSException {
		this.instructorHistoryIDSet.clear();

		this.tblMain.removeRows();
		if (this.prmtTrainCourse.getValue() != null) {
			TrainCourseInfo trainCourseInfo = (TrainCourseInfo) this.prmtTrainCourse
					.getValue();
			this.trainCourseID = trainCourseInfo.getId().toString();
			EntityViewInfo evi = new EntityViewInfo();
			FilterInfo fi = new FilterInfo();
			fi.getFilterItems().add(
					new FilterItemInfo("TrainCourse.id", trainCourseInfo
							.getId().toString()));
			fi.getFilterItems().add(
					new FilterItemInfo("trainChannel.id", null,
							CompareType.EQUALS));
			evi.setFilter(fi);
			evi.getSelector().add(new SelectorItemInfo("id"));
			evi.getSelector().add(new SelectorItemInfo("Instructor.*"));
			evi.getSelector().add(
					new SelectorItemInfo("Instructor.Employee.id"));
			evi.getSelector().add(
					new SelectorItemInfo("Instructor.Employee.name"));
			evi.getSelector().add(
					new SelectorItemInfo("Instructor.Employee.cell"));
			evi.getSelector().add(
					new SelectorItemInfo("Instructor.InstructorType.id"));
			evi.getSelector().add(
					new SelectorItemInfo("Instructor.InstructorType.name"));
			evi.getSorter().add(new SorterItemInfo("Instructor.name"));
			ChannelCoursE1Collection collection = ChannelCoursE1Factory
					.getRemoteInstance().getChannelCoursE1Collection(evi);

			if ((collection != null) && (collection.size() > 0)) {
				Object[] objs = new Object[collection.size()];
				for (int i = 0; i < collection.size(); i++) {
					ChannelCoursE1Info channelCoursE1Info = collection.get(i);
					TrainInstructorInfo trainInstructorInfo = channelCoursE1Info
							.getInstructor();
					this.instructorHistoryIDSet.add(trainInstructorInfo.getId()
							.toString());
					objs[i] = trainInstructorInfo;
				}
				dealAddInstructor(objs);
			}
		}
	}

	private void init() {
		this.prmtTrainCourse.setEditable(false);
		this.tblMain.getStyleAttributes().setLocked(true);

		TrainCoursePromptBox promptBox = new TrainCoursePromptBox(this);
		SelectorItemCollection sic = new SelectorItemCollection();
		sic.add(new SelectorItemInfo("id"));
		sic.add(new SelectorItemInfo("name"));
		sic.add(new SelectorItemInfo("number"));
		sic.add(new SelectorItemInfo("CourseHour"));
		sic.add(new SelectorItemInfo("CourseHourUnit"));
		sic.add(new SelectorItemInfo("CourseJoinner"));
		sic.add(new SelectorItemInfo("CourseTarget"));
		sic.add(new SelectorItemInfo("courseCost"));
		sic.add(new SelectorItemInfo("CourseKind.name"));
		sic.add(new SelectorItemInfo("treeid.name"));
		promptBox.setSelector(sic);
		this.prmtTrainCourse.setSelector(promptBox);

		TrainCourseInfo info_byCourse = (TrainCourseInfo) getUIContext().get(
				TrainConstants.TRAINCOURSE);
		this.prmtTrainCourse.setValue(info_byCourse);

		TrainUtils.setMutilTableFromBIM(this.contInstructor, this.tblMain);
		JButton button = this.contInstructor.add(this.actionAddInstructor);
		button.setIcon(EASResource.getIcon("imgTbtn_addline"));
		button.setToolTipText(EASResource.getString(
				"com.kingdee.eas.hr.train.client.TrainChanneResource",
				"addInstructor"));
		this.actionAddInstructor.setEnabled(true);
		button = this.contInstructor.add(this.actionRemoveInstructor);
		button.setIcon(EASResource.getIcon("imgTbtn_deleteline"));
		button.setToolTipText(EASResource.getString(
				"com.kingdee.eas.hr.train.client.TrainChanneResource",
				"removeInstructor"));
		this.actionRemoveInstructor.setEnabled(true);
		this.btnSave.setIcon(EASResource.getIcon("imgTbtn_save"));
		this.btnLocate.setIcon(EASResource.getIcon("imgTbtn_speedgoto"));
		this.btnSave.setEnabled(true);
		this.btnLocate.setEnabled(true);

		this.instructorPromptBox = new TrainInstructorPromptBox(this);
		sic = new SelectorItemCollection();
		sic.add(new SelectorItemInfo("id"));
		sic.add(new SelectorItemInfo("name"));
		sic.add(new SelectorItemInfo("number"));
		sic.add(new SelectorItemInfo("isOuter"));
		sic.add(new SelectorItemInfo("MobilePhone"));
		sic.add(new SelectorItemInfo("Special"));
		sic.add(new SelectorItemInfo("Employee.name"));
		sic.add(new SelectorItemInfo("Employee.cell"));
		sic.add(new SelectorItemInfo("InstructorType.name"));
		this.instructorPromptBox.setSelector(sic);
		this.instructorPromptBox.setSingleSelect(false);
	}

	public void actionAddInstructor_actionPerformed(ActionEvent e)
			throws Exception {
		this.instructorPromptBox.show();
		if ((!this.instructorPromptBox.isCanceled())
				&& ((this.instructorPromptBox.getData() instanceof Object[]))) {
			final Object[] objs = (Object[]) this.instructorPromptBox.getData();

			if (objs.length > 10) {
				ProgressManager.DaemonTask process = new ProgressManager.DaemonTask() {

					public void run() throws Exception {
						BatchAddInstructorForCourseUI.this
								.dealAddInstructor(objs);
					}
				};
				new ProgressManager(this).launchProcess(process, this);
			} else {
				dealAddInstructor(objs);
			}
		}
	}

	public void actionRemoveInstructor_actionPerformed(ActionEvent e)
			throws Exception {
		TrainUtils.removeLine(this.tblMain);
	}

	private void dealAddInstructor(Object[] objs) throws BOSException {
		if ((objs != null) && (objs.length > 0)) {
			IRow row = null;
			TrainInstructorInfo trainInstructorInfo = null;

			setPersonSpecial(objs);
			int i = 0;
			for (int length = objs.length; i < length; i++) {
				trainInstructorInfo = (TrainInstructorInfo) objs[i];
				if (TrainUtils.isRepeatRowInTable(this.tblMain,
						trainInstructorInfo.getNumber(), "number")) {
					continue;
				}
				row = this.tblMain.addRow();
				setDataToRow(trainInstructorInfo, row);
			}
		}
	}

	private void setPersonSpecial(Object[] objs) throws BOSException {
		Set personIds = null;
		TrainInstructorInfo trainInstructorInfo = null;
		int i = 0;
		Map map = new HashMap();
		for (int length = objs.length; i < length; i++) {
			trainInstructorInfo = (TrainInstructorInfo) objs[i];
			if (!trainInstructorInfo.isIsOuter()) {
				if (personIds == null)
					personIds = new HashSet();
				personIds.add(trainInstructorInfo.getEmployee().getId()
						.toString());
			}
		}
		if (personIds != null) {
			EntityViewInfo viewInfo = new EntityViewInfo();
			viewInfo.getSelector().add(new SelectorItemInfo("specialty.*"));
			viewInfo.getSelector().add(new SelectorItemInfo("person.id"));
			FilterInfo filterInfo = new FilterInfo();
			filterInfo.getFilterItems().add(
					new FilterItemInfo("person.id", personIds,
							CompareType.INCLUDE));
			filterInfo.getFilterItems().add(
					new FilterItemInfo("isHighest", new Integer(1)));
			viewInfo.setFilter(filterInfo);
			PersonDegreeCollection degreeCollection = PersonDegreeFactory
					.getRemoteInstance().getPersonDegreeCollection(viewInfo);
			if ((degreeCollection != null) && (degreeCollection.size() > 0)) {
				if (this.personDegrees == null)
					this.personDegrees = new HashMap();
				else {
					this.personDegrees.clear();
				}
				PersonDegreeInfo personDegreeInfo = null;
				int j = 0;
				for (int size = degreeCollection.size(); j < size; j++) {
					personDegreeInfo = degreeCollection.get(j);
					this.personDegrees
							.put(
									personDegreeInfo.getPerson().getId(),
									personDegreeInfo.getSpecialty() == null ? null
											: personDegreeInfo.getSpecialty()
													.getName());

				}
			}
		}
	}

	private void setDataToRow(Object object, IRow row) {
		TrainInstructorInfo info = (TrainInstructorInfo) object;
		row.getCell("instructorObject").setValue(info);
		row.getCell("number").setValue(info.getNumber());
		if (info.getInstructorType() != null) {
			row.getCell("type").setValue(info.getInstructorType().getName());
		}
		if (info.isIsOuter()) {
			row.getCell("name").setValue(info.getName());
			row.getCell("backgroud").setValue(info.getSpecial());
			row.getCell("phone").setValue(info.getMobilePhone());
			row.getCell("kind").setValue(
					EASResource.getString(
							"com.kingdee.eas.hr.train.client.TrainSysResource",
							"OuterInstructor"));
		} else {
			PersonInfo person = info.getEmployee();
			row.getCell("name").setValue(person.getName());
			if (this.personDegrees != null) {
				row.getCell("backgroud").setValue(
						this.personDegrees.get(person.getId()));
			}
			row.getCell("phone").setValue(person.getCell());
			row.getCell("kind").setValue(
					EASResource.getString(
							"com.kingdee.eas.hr.train.client.TrainSysResource",
							"InnerInstructor"));
		}
	}

	private void checkModify(PreChangeEvent event) {
		if (isModify()) {
			int result = MsgBox
					.showConfirm3(
							this,
							EASResource
									.getString("com.kingdee.eas.framework.FrameWorkResource.Confirm_Save_Check"));
			if (result == 0)
				operateYes();
			else if (result == 2)
				if (event != null)
					event.setResult(0);
				else
					SysUtil.abort();
		}
	}

	private boolean isModify() {
		try {
			ControlUtilities.checkFocusAndCommit();
		} catch (ParseException e) {
			handleControlException();
			abort();
		}

		isNeedDeal();

		return (this.instructorAddIDSet.size() != 0)
				|| (this.instructorRemoveIDSet.size() != 0);
	}

	private void isNeedDeal() {
		this.instructorAddIDSet.clear();
		this.instructorRemoveIDSet.clear();

		Set instructorIDSetFromTable = new HashSet();
		if (this.tblMain.getRowCount() > 0) {
			int i = 0;
			for (int count = this.tblMain.getRowCount(); i < count; i++) {
				TrainInstructorInfo instructorInfo = (TrainInstructorInfo) this.tblMain
						.getRow(i).getCell("instructorObject").getValue();
				instructorIDSetFromTable.add(instructorInfo.getId().toString());
				if (!this.instructorHistoryIDSet.contains(instructorInfo
						.getId().toString())) {
					this.instructorAddIDSet.add(instructorInfo.getId()
							.toString());
				}
			}

		}

		if ((this.instructorHistoryIDSet != null)
				&& (this.instructorHistoryIDSet.size() > 0)) {
			Iterator iterator = this.instructorHistoryIDSet.iterator();

			while (iterator.hasNext()) {
				String id_tmp = (String) iterator.next();
				if (!instructorIDSetFromTable.contains(id_tmp))
					this.instructorRemoveIDSet.add(id_tmp);
			}
		}
	}

	private void operateYes() {
		ActionEvent event = new ActionEvent(this.btnSave, 1001, this.btnSave
				.getActionCommand());
		this.actionSave.actionPerformed(event);
		if (this.actionSave.isInvokeFailed())
			SysUtil.abort();
	}

	public void actionSave_actionPerformed(ActionEvent e) throws Exception {
		super.actionSave_actionPerformed(e);
		isNeedDeal();

		String notDelMessage = ChannelCoursE1Factory.getRemoteInstance()
				.batchAddInstructorForCourse(this.instructorAddIDSet,
						this.instructorRemoveIDSet, this.trainCourseID);

		if (notDelMessage != null) {
			MsgBox.showInfo(notDelMessage);
		} else {
			TrainClientUtil.showMessage(
					"com.kingdee.eas.hr.train.client.TrainRecordResource",
					"batchSaveSuccess", this);
		}
		if ((this.instructorAddIDSet != null)
				&& (this.instructorAddIDSet.size() > 0)) {
			Iterator iterator = this.instructorAddIDSet.iterator();
			while (iterator.hasNext()) {
				this.instructorHistoryIDSet.add(iterator.next().toString());
			}
		}
		if ((this.instructorRemoveIDSet != null)
				&& (this.instructorRemoveIDSet.size() > 0)) {
			Iterator iterator = this.instructorRemoveIDSet.iterator();
			while (iterator.hasNext()) {
				this.instructorHistoryIDSet.remove(iterator.next().toString());
			}
		}
		loadData();
	}

	public void actionLocate_actionPerformed(ActionEvent e) throws Exception {
		super.actionLocate_actionPerformed(e);
		if (this.locateAssistant == null) {
			this.locateAssistant = new LocateAssistant(this, this.tblMain,
					getLocateNames());
		}

		this.locateAssistant.actionLocate();
	}

	protected String[] getLocateNames() {
		String[] locateNames = new String[4];
		locateNames[0] = TrainConstants.NUMBER;
		locateNames[1] = TrainConstants.NAME;
		return locateNames;
	}

	protected boolean checkBeforeWindowClosing() {
		checkModify(null);
		return super.checkBeforeWindowClosing();
	}
}